package org.gitee.weapp.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.gitee.weapp.domain.AjaxResult;
import org.gitee.weapp.domain.common.constant.Constant;
import org.gitee.weapp.domain.entity.Coupon;
import org.gitee.weapp.domain.entity.Order;
import org.gitee.weapp.domain.entity.SysUser;
import org.gitee.weapp.mapper.CouponMapper;
import org.gitee.weapp.mapper.OrderMapper;
import org.gitee.weapp.service.OrderService;
import org.gitee.weapp.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CouponMapper couponMapper;


    /**
     * 生成20位订单id
     * @return
     */
    public static String createOrderId() {
        StringBuilder date = new StringBuilder(DateUtils.getDateString());
        Random rd = new Random();
        String value = String.valueOf(rd.nextInt(1000));
        for (int i=0; i < 3 - value.length(); i++) {
            date.append('0');
        }
        date.append(value);
        return date.toString();
    }

    @Override
    @Transactional
    public void addOrder(Order order, SysUser sysUser) {
        order.setId(createOrderId());
        order.setUserId(sysUser.getOpenId());
        order.setPayTime(DateUtils.getNowDate());
        order.setType(Constant.ORDER_PAYED);

        if (null != order.getCouponId()) {
            Coupon coupon = couponMapper.getCouponById(order.getCouponId());
            if (null == coupon || !StringUtils.equals(coupon.getUserId(), order.getUserId())) {
                throw new RuntimeException("优惠券不存在");
            }
            if (coupon.getUsed()) {
                throw new RuntimeException("优惠券已使用");
            }
            coupon.setUsed(true);
            couponMapper.update(coupon);
        }
        orderMapper.insert(order);
        orderMapper.insertOrderCount(order.getId(), order.getGoodsCount());
    }

    public static void main(String[] args) {
        System.out.println(createOrderId());
    }
}
